const res = require('express/lib/response')
const db = require('../db/index')

// 查询所有文章分类
exports.getArtcate = (req, res) => {


    const sql = `SELECT * FROM ev_article_cate WHERE is_delete=0 ORDER BY id ASC `


    db.query(sql, (err, results) => {

        if (err) return res.cc(err)

        res.send({
            status: 0,
            message: "success",
            data: results
        })

    })


}

// 新增文章分类

exports.addArtcate = (req, res) => {

    const sql = `SELECT * FROM ev_article_cate WHERE name =? OR alias =?`

    db.query(sql, [req.body.name, req.body.alias], (err, results) => {
        if (err) return res.cc(err)
        if (results.length == 2) return res.cc('名称和别名都已被占用')
        if (results.length == 1 && results[0].name == req.body.name && results[0].alias == req.body.alias) return res.cc('名称或者别名被占用')
        if (results.length == 1 && results[0].name == req.body.name) return res.cc('名称被占用')
        if (results.length == 1 && results[0].alias == req.body.alias) return res.cc('别名被占用')

        const sql = `INSERT INTO  ev_article_cate SET ?`

        db.query(sql, req.body, (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows !== 1) return res.cc('新增失败')
            res.cc('新增成功', 0)
        })
    })

}

// 根据id删除文章分类

exports.deleteArtcate = (req, res) => {
    const sql = `UPDATE ev_article_cate SET is_delete = 1 WHERE id =?`

    db.query(sql, req.params.id, (err, results) => {
        if (err) return res.cc(err)

        if (results.affectedRows !== 1) return res.cc('删除文章失败')
        res.cc('删除成功', 0)
    })

}